package com.itany.utils;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyHttpClientUtils {


    /**
     * Get 请求
     * @param url
     * @return
     */
    public static String doGet(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result="";
        try {
          /*  //声明代理对象
            HttpHost proxy = new HttpHost("202.46.38.11",		8080,"HTTP");
            //声明请求配置对象
            RequestConfig config = RequestConfig.custom()
                    .setProxy(proxy)
                    .setConnectTimeout(10000)
                    .setSocketTimeout(10000)
                    .setConnectionRequestTimeout(10000).build();*/
            HttpGet get = new HttpGet(url);
           /* get.setConfig(config);*/
            response = httpClient.execute(get);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(httpClient, response);
        }
        return  result;
    }


    /**
     * Post 请求
     * @return
     */
    public static String doPost(String url, Map<String,String> params){
        //创建http客户端对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //声明返回值
        String result="";
        //声明响应对象
        CloseableHttpResponse response = null;
        try {
             //构建请求对象
            HttpPost post = new HttpPost(url);
            //构建参数
            if(params!=null){
                List<NameValuePair> paramList =  new ArrayList<NameValuePair>();
                for(Map.Entry<String,String> param : params.entrySet()){
                    paramList.add(new BasicNameValuePair(param.getKey(),param.getValue()));
                }
                //声明form对象
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, Charset.defaultCharset());
                post.setEntity(formEntity);
            }
            //执行请求
            response = httpClient.execute(post);
            //判断响应状态
             if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                 result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
             }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(httpClient, response);
        }

        return result;
    }

    private static void close(CloseableHttpClient httpClient,
                              CloseableHttpResponse response){
           try {

               if(response!=null){
                    response.close();
               }

               if(httpClient!=null){
                   httpClient.close();
               }

           }catch (Exception e){
               e.printStackTrace();
           }
    }


/*    public static void main(String[] args) {
        //获取页面html代码
        String html= MyHttpClientUtils.doGet("http://www.bookschina.com");
        //将html字符串解析成dom对象
        Document document = Jsoup.parse(html,"UTF-8");
        //通过class选择器获取当前页面的对应元素
        Elements plist = document.getElementsByClass("c-category-list");
        for(int i=0;i<plist.size();i++){
            Element p = plist.get(i);
            Elements alist = p.getElementsByTag("a");
            for(int j=0;j<alist.size();j++){
                System.out.println(alist.get(j).attr("href")+"=================="+alist.get(j).text());
            }
        }
    }*/


    public static void main(String[] args) {
//        String isbn = "9787111213826";
//        String get = MyHttpClientUtils.doGet("http://feedback.api.juhe.cn/ISBN?key=303033e62d74312d1a9a72464b485517&sub=" + isbn);


//        System.out.println(get);

    }


}
